package cn.pengpeng.curd;

import java.util.ArrayList;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellScanner;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;
import org.apache.hadoop.hbase.filter.Filter;
import org.apache.hadoop.hbase.filter.RowFilter;
import org.apache.hadoop.hbase.filter.SubstringComparator;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.Test;

public class HbaseDemo {

	// 建表
	@Test
	public void testCreateTable() throws Exception {
		// Configuration conf = new Configuration(); //
		// 会加载classpath中的core-site.xml,hdfs-site.xml等配置文件，但不会加载hbase-site.xml
		Configuration conf = HBaseConfiguration.create();

		conf.set("hbase.zookeeper.quorum", "bigdata01:2181,bigdata02:2181,bigdata03:2181");

		// 创建连接
		Connection conn = ConnectionFactory.createConnection(conf);

		// 从连接中获取一个表管理器对象
		Admin admin = conn.getAdmin();
		// 创建一个表描述信息封装器
		HTableDescriptor hTableDescriptor = new HTableDescriptor(TableName.valueOf("t_test2"));
		// 创建一个列族描述器
		HColumnDescriptor hColumnDescriptor1 = new HColumnDescriptor("f1");
		hColumnDescriptor1.setMaxVersions(3);

		HColumnDescriptor hColumnDescriptor2 = new HColumnDescriptor("f2");

		// 将列族描述加入到表描述器
		hTableDescriptor.addFamily(hColumnDescriptor1);
		hTableDescriptor.addFamily(hColumnDescriptor2);

		// 将表描述器交给admin去创建
		admin.createTable(hTableDescriptor);

		admin.close();
		conn.close();

	}

	// 删除表
	@Test
	public void testDropTable() throws Exception {

		Configuration conf = HBaseConfiguration.create();

		conf.set("hbase.zookeeper.quorum", "hdp27-01:2181,hdp27-02:2181,hdp27-03:2181");

		// 创建连接
		Connection conn = ConnectionFactory.createConnection(conf);

		Admin admin = conn.getAdmin();

		admin.disableTable(TableName.valueOf("t_test"));
		admin.deleteTable(TableName.valueOf("t_test"));

		admin.close();
		conn.close();
	}

	// 增 /改
	@Test
	public void testPutData() throws Exception {

		Configuration conf = HBaseConfiguration.create();

		conf.set("hbase.zookeeper.quorum", "hdp27-01:2181,hdp27-02:2181,hdp27-03:2181");

		// 创建连接
		Connection conn = ConnectionFactory.createConnection(conf);

		// 先从conn中拿到一个表操作工具
		Table table = conn.getTable(TableName.valueOf("t_test2"));

		// 封装要插入的数据
		Put put1 = new Put("001".getBytes());
		put1.addColumn("f1".getBytes(), "name".getBytes(), "张三".getBytes());
		put1.addColumn("f1".getBytes(), "age".getBytes(), Bytes.toBytes(18));

		Put put2 = new Put("002".getBytes());
		put2.addColumn("f1".getBytes(), "name".getBytes(), "张一三".getBytes());
		put2.addColumn("f1".getBytes(), "age".getBytes(), Bytes.toBytes(28));

		ArrayList<Put> puts = new ArrayList<>();
		puts.add(put1);
		puts.add(put2);

		// 交给table对象去插入
		table.put(puts);

		table.close();
		conn.close();

	}

	// 删数据
	@Test
	public void testDeleteData() throws Exception {
		Configuration conf = HBaseConfiguration.create();

		conf.set("hbase.zookeeper.quorum", "hdp27-01:2181,hdp27-02:2181,hdp27-03:2181");

		// 创建连接
		Connection conn = ConnectionFactory.createConnection(conf);

		Table table = conn.getTable(TableName.valueOf("t_test2"));

		Delete delete = new Delete("001".getBytes());
		// 如果指定key，则只删该key。如果不指定，则删除001行的所有key
		delete.addColumn("f1".getBytes(), "name".getBytes());

		table.delete(delete);

		table.close();

	}

	// 查
	@Test
	public void testGetData() throws Exception {
		Configuration conf = HBaseConfiguration.create();

		conf.set("hbase.zookeeper.quorum", "hdp27-01:2181,hdp27-02:2181,hdp27-03:2181");

		// 创建连接
		Connection conn = ConnectionFactory.createConnection(conf);

		Table table = conn.getTable(TableName.valueOf("t_test2"));

		Get get = new Get("002".getBytes());
		// get.addColumn("f1".getBytes(), "name".getBytes());

		Result result = table.get(get); // result就是多个kv的封装
		CellScanner cellScanner = result.cellScanner();
		while (cellScanner.advance()) {
			Cell cell = cellScanner.current();
			byte[] rowArray = cell.getRowArray();// 获取这个keyvalue所属的行键字节
			byte[] familyArray = cell.getFamilyArray(); // 获取这个keyvalue所属的列族字节
			byte[] qualifierArray = cell.getQualifierArray(); // 获取这个keyvalue的key字节
			byte[] valueArray = cell.getValueArray(); // 获取这个keyvalue的value字节

			System.out.print(new String(rowArray, cell.getRowOffset(), cell.getRowLength()));
			System.out.print(" | ");
			System.out.print(new String(familyArray, cell.getFamilyOffset(), cell.getFamilyLength()));
			System.out.print(" | ");
			String key = new String(qualifierArray, cell.getQualifierOffset(), cell.getQualifierLength());
			System.out.print(key);
			System.out.print(" | ");
			if (key.equals("age")) {
				// 如果是age，就将value转成整数
				System.out.println(Bytes.toInt(valueArray, cell.getValueOffset(), cell.getValueLength()));
			} else {
				// 如果不是age，则将value转成字符串
				System.out.println(Bytes.toString(valueArray, cell.getValueOffset(), cell.getValueLength()));
			}
		}

	}
	
	
	/**
	 * 范围查询
	 * @throws Exception
	 */
	@Test
	public void testScan() throws Exception {
		Configuration conf = HBaseConfiguration.create();

		conf.set("hbase.zookeeper.quorum", "hdp27-01:2181,hdp27-02:2181,hdp27-03:2181");

		// 创建连接
		Connection conn = ConnectionFactory.createConnection(conf);

		Table table = conn.getTable(TableName.valueOf("t_test2"));
		
		// 含首不含尾
		Scan scan = new Scan("002".getBytes(), "004\000".getBytes());
		scan.addColumn("f1".getBytes(), "name".getBytes());
		
		ResultScanner scanner = table.getScanner(scan);
		for (Result result : scanner) {
			System.out.println(new String(result.getValue("f1".getBytes(), "name".getBytes())));
		}
		
		table.close();
		conn.close();
		
	}
	
	
	
	/**
	 * 条件查询：用过滤器实现
	 * @throws Exception 
	 */
	@Test
	public void testFilterScan() throws Exception {
		
		Configuration conf = HBaseConfiguration.create();

		conf.set("hbase.zookeeper.quorum", "hdp27-01:2181,hdp27-02:2181,hdp27-03:2181");

		// 创建连接
		Connection conn = ConnectionFactory.createConnection(conf);

		Table table = conn.getTable(TableName.valueOf("t_test2"));
		
		Scan scan = new Scan("002".getBytes());
		scan.addColumn("f1".getBytes(), "name".getBytes());
		
		// 前缀过滤器：针对行键的
		//Filter filter = new PrefixFilter("zhang".getBytes());
		
		// 参数1： 比较操作符> < >= <= == !=  参数2：条件值
		// 前缀过滤器：针对行键的
		//Filter filter = new RowFilter(CompareOp.EQUAL, new BinaryComparator("0040".getBytes()));
		//Filter filter = new RowFilter(CompareOp.LESS, new BinaryComparator("0040".getBytes()));
		Filter filter = new RowFilter(CompareOp.EQUAL, new SubstringComparator("04"));
		
		// 为scan设置一个过滤器
		scan.setFilter(filter);
		
		ResultScanner scanner = table.getScanner(scan);
		for (Result result : scanner) {
			System.out.println(new String(result.getValue("f1".getBytes(), "name".getBytes())));
		}
		
		
		table.close();
		conn.close();
	}
}
